<script setup lang="ts">
import { ref, computed } from 'vue'
import { getStoredUser } from '../../api/auth'
import UserList from './UserList.vue'
import UserForm from './UserForm.vue'
import type { UserInfo } from '../../api/user'

// 引用子组件实例
const userListRef = ref<InstanceType<typeof UserList> | null>(null)

// 对话框控制
const createUserDialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditUser = ref<UserInfo | null>(null)

// 从localStorage获取用户信息
const currentUser = computed(() => {
  return getStoredUser() || {username: '用户', nickname: '用户', role: 3}
})

// 角色选项
const roleOptions = [
  { value: 1, label: '超级管理员' },
  { value: 2, label: '管理员' },
  { value: 3, label: '普通用户' }
]

// 获取当前用户可以创建的角色选项
const getAvailableRoles = computed(() => {
  if (currentUser.value?.role === 1) { // 超级管理员
    return roleOptions.filter(role => role.value >= 2) // 可以创建管理员和普通用户
  } else if (currentUser.value?.role === 2) { // 管理员
    return roleOptions.filter(role => role.value === 3) // 只能创建普通用户
  }
  return []
})

// 显示创建用户对话框
const handleCreateUser = () => {
  isEditMode.value = false
  currentEditUser.value = null
  createUserDialogVisible.value = true
}

// 显示编辑用户对话框
const handleEditUser = (user: UserInfo) => {
  isEditMode.value = true
  currentEditUser.value = user
  createUserDialogVisible.value = true
}

// 用户创建成功后刷新列表
const handleUserCreated = () => {
  if (userListRef.value) {
    userListRef.value.fetchUserList()
  }
}
</script>

<template>
  <div class="user-manager">
    <!-- 用户列表组件 -->
    <UserList 
      ref="userListRef"
      @create-user="handleCreateUser"
      @edit-user="handleEditUser"
    />
    
    <!-- 用户表单组件 -->
    <UserForm
      v-model:visible="createUserDialogVisible"
      :available-roles="getAvailableRoles"
      :is-edit-mode="isEditMode"
      :edit-user="currentEditUser"
      @success="handleUserCreated"
    />
  </div>
</template>

<style scoped>
.user-manager {
  width: 100%;
}
</style> 